//
//  FSRViewController.m
//  Estate
//
//  Created by heyong on 16/6/12.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "FSRViewController.h"
#import "B_RenCell.h"
#import "QianDTableCell.h"
#import "B_SwitchCell.h"
#import "PictureViewController.h"



@interface FSRViewController ()

@end

@implementation FSRViewController

-(NSMutableArray *)selectedAssetURLs{
    if(_selectedAssetURLs==nil){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return  _selectedAssetURLs;
}

- (NSMutableDictionary *)dataDic{
    if(_dataDic==nil){
        _dataDic=[NSMutableDictionary dictionary];
        
    }
    return _dataDic;
}

- (Site_02 *)site{
    if(_site==nil){
        _site=[[Site_02 alloc]init];
    }
    return _site;
}

-(TPKeyboardAvoidingTableView *)tableView{
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [LSUtility setExtraCellLineHidde:self.tableView tabHeader:NO tabFooter:NO];
        //注册表格
        [_tableView registerNib:[UINib nibWithNibName:@"B_RenCell" bundle:nil] forCellReuseIdentifier:@"ren"];
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"index"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_SwitchCell" bundle:nil] forCellReuseIdentifier:@"switch"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_RenCell" bundle:nil] forCellReuseIdentifier:@"ren"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
    }
    return _tableView;
}
- (UIImagePickerController *)picker{
    if(!_picker){
       _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = NO;//设置可编辑
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _picker;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    //添加表格
    [self.view addSubview:self.tableView];
    //附件模型
    _curTweet = [[Tweet alloc] init];
    
    [self setData];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_2" object:nil];
}

- (void)refresh:(id)sender{
    //存在图片
    if(self.selectedAssetURLs!=nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //设置图片
            self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
            //回到主线程来刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }

}


- (void)setData{
    WEAKSELF
    //查看页
    if(_site!=nil){
        [weakSelf.dataDic setObject:_site.zaigangNum forKey:@"施工单位质检在岗人员"];
        [weakSelf.dataDic setObject:_site.gongbanNum forKey:@"工班人数"];
        [weakSelf.dataDic setObject:_site.teshuNum forKey:@"施工人数"];
        [weakSelf.dataDic setObject:_site.guanliNum forKey:@"管理人数"];
        [weakSelf.dataDic setObject:_site.isR forKey:@"是否满足施工组织需要"];
        self.selectedAssetURLs= [LSUtility quertFileImageType:@"RECORD_02_SIDE_01" andId:_site.recordId andFilePathArr:_site.fileArray];
        [self refresh:nil];
    }else{
        //默认为nil
        [weakSelf.dataDic setObject:@"" forKey:@"施工单位质检在岗人员"];
        [weakSelf.dataDic setObject:@"" forKey:@"工班人数"];
        [weakSelf.dataDic setObject:@"" forKey:@"施工人数"];
        [weakSelf.dataDic setObject:@"" forKey:@"管理人数"];
        [weakSelf.dataDic setObject:@"是" forKey:@"是否满足施工组织需要"];
    }
    
}


#pragma mark- UITableViewDelagate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0;
    }else{
        return 10;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 5;
    }else{
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
    }else{
        return 44;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    long section=indexPath.section;
    if(section==0){
        if(indexPath.row==0){
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"index" forIndexPath:indexPath];
            //能否编辑
            cell.isedit=self.isEdit;
            cell.textValueChangedBlock=^(NSString *valueStr){
                weakSelf.site.zaigangNum=valueStr;
                [ weakSelf.dataDic setObject:valueStr forKey:@"施工单位质检在岗人员"];
            };
            if(_site.zaigangNum){
                cell.textField.text=_site.zaigangNum;
                [ weakSelf.dataDic setObject:_site.zaigangNum forKey:@"施工单位质检在岗人员"];
            }
            [cell configWithPlaceholder:@"姓名" andValue:weakSelf.site.zaigangNum andLabel:@"施工单位质检在岗人员:" andKeyType:UIKeyboardTypeDefault];
            return cell;
            
        }else if(indexPath.row==1){
            B_RenCell *cells=[tableView dequeueReusableCellWithIdentifier:@"ren" forIndexPath:indexPath];
            cells.renBlock= ^(NSString * valueStr){
                weakSelf.site.gongbanNum=valueStr;
                [ weakSelf.dataDic setObject:weakSelf.site.gongbanNum forKey:@"工班人数"];
            };
            
            cells.isEdit=weakSelf.isEdit;
            if(_site.gongbanNum){
                cells.num.text=weakSelf.site.gongbanNum;
            }
            
            [cells configWithPlaceholder:@"请输入" andValue:weakSelf.site.gongbanNum andLabel:@"工班人数:" andKeyType:UIKeyboardTypeNumberPad];
            return cells;
            
        }else if (indexPath.row==2){
            B_RenCell *cells=[tableView dequeueReusableCellWithIdentifier:@"ren" forIndexPath:indexPath];
            cells.selectionStyle=UITableViewCellSelectionStyleNone;
            cells.renBlock= ^(NSString * valueStr){
                weakSelf.site.guanliNum=valueStr;
                [ weakSelf.dataDic setObject:weakSelf.site.guanliNum forKey:@"管理人数"];
            };
            cells.isEdit=weakSelf.isEdit;
            if(_site){
                cells.num.text=weakSelf.site.guanliNum;
            }
            
            
            [cells configWithPlaceholder:@"请输入" andValue:weakSelf.site.guanliNum andLabel:@"管理人数:" andKeyType:UIKeyboardTypeNumberPad];
            return cells;
            
        }else if(indexPath.row==3){
            B_RenCell *cells=[tableView dequeueReusableCellWithIdentifier:@"ren" forIndexPath:indexPath];
            cells.selectionStyle=UITableViewCellSelectionStyleNone;
            cells.renBlock=^(NSString *valueStr){
                weakSelf.site.teshuNum=valueStr;
                [ weakSelf.dataDic setObject:weakSelf.site.teshuNum forKey:@"施工人数"];
            };
            cells.isEdit=weakSelf.isEdit;
            if(_site.teshuNum){
                cells.num.text=weakSelf.site.teshuNum;
            }
            
            [cells configWithPlaceholder:@"请输入" andValue:weakSelf.site.teshuNum andLabel:@"施工人数:" andKeyType:UIKeyboardTypeNumberPad];
            return cells;
        }else{
            B_SwitchCell *cells=[tableView dequeueReusableCellWithIdentifier:@"switch" forIndexPath:indexPath];
            
            cells.isEdit=weakSelf.isEdit;

            cells.sValueChangeBlock=^(UISwitch *sender){
                weakSelf.site.isR=sender.on==0?@"否":@"是";
                [weakSelf.dataDic setObject:weakSelf.site.isR forKey: @"是否满足施工组织需要"];
                
            };
            if(_site.isR){
                if([_site.isR isEqualToString:@"是"]){
                    //设置开关
                    [cells.kaiguan setOn:YES];
                }else{
                    [cells.kaiguan setOn:NO];
                }
            }
            return  cells;
        }
    }else{
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit=self.isEdit;
        [cell setTitle:@"附件"];
        cell.curTweet = _curTweet;
        //添加图片
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        __block H1_ImagesCell *cellblock = cell;
        cell.deleteTweetImageBlockUrl = ^(TweetImage *toDelete,NSString *deurl){
            [cellblock.curTweet.tweetImages removeObject:toDelete];
            [weakSelf.selectedAssetURLs removeObject:deurl];
            [weakSelf refresh:nil];
        };
        return cell;
    }
}

#
#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
       
        [self presentViewController:self.picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages=[[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            for (NSString *path in array) {
                //添加图片路径到已选数组
                [self.selectedAssetURLs addObject:path];
            }
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark scrollview
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
